package com.pmgames.store.data
{
	import com.pmgames.store.events.JavaFlexBoundaryConditionEvent;
	import com.pmgames.store.events.JavaFlexGameOverEvent;
	
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;

	public class WordToGuess_Hgm  extends EventDispatcher
	{
		private var word:WordItem;
		public var lettersToOpen:int;
		private var stepsBeforeLose:int;
		
		public function WordToGuess_Hgm(source:RelationArrayCollection = null, stepsBeforeLose:int = 0):void
		{
			if(source != null)
			{
				word = RelationItem(source.getItemAt(source.length - 1)).sourceId;
				setLettersToOpen();
				this.stepsBeforeLose = stepsBeforeLose;
			}
		}
			
		private function setLettersToOpen():void
		{
			lettersToOpen = word.name.length-1;
		}
				
		public function getWord():WordItem
		{
			return word;
		}	
		
		public function decrementLettersToOpen():int
		{
			lettersToOpen--;
			return lettersToOpen;
		} 
		
		public function decrementStepsBeforLose():int
		{
			stepsBeforeLose--;
			return stepsBeforeLose;
		}
		
		public function getLetterIndexes(letter:String):ArrayCollection
		{
			var indexes:ArrayCollection = new ArrayCollection();
			var index:int = word.name.toUpperCase().indexOf(letter);
			while(index >= 0)
			{
				indexes.addItem(index);
				index = word.name.toUpperCase().indexOf(letter, index + 1);				
			}
			return indexes;
		}
		
		
		public function addLetterToWord(letter:String):void
		{
			var index:int = word.name.toUpperCase().indexOf(letter);
			if(index < 0)
			{
				if(decrementStepsBeforLose() == 1)
				{
					dispatchEvent(new JavaFlexGameOverEvent(JavaFlexGameOverEvent.WORD_NOT_GUESSED));
				}
				else
				{
					dispatchEvent(new JavaFlexBoundaryConditionEvent(JavaFlexBoundaryConditionEvent.BOUNDARY_CONDITION, stepsBeforeLose));
				}
			}				
			while(index >= 0)
			{
				index = word.name.toUpperCase().indexOf(letter, index + 1);
				if(decrementLettersToOpen() == -1)
				{
					dispatchEvent(new JavaFlexGameOverEvent(JavaFlexGameOverEvent.WORD_GUESSED));
				}
			}
		}
	}
}